package sql

import (
	"gorm.io/gorm"
	"gorm.io/gorm/clause"

	"vov.cx/lib/errs"
)

func IfNotFound(tx *gorm.DB) error {
	if tx.Error == nil || errs.Is(tx.Error, gorm.ErrRecordNotFound) {
		return nil
	}
	return tx.Error
}

func DoNothingOnConflict() clause.OnConflict {
	return clause.OnConflict{DoNothing: true}
}

func OrderByCreatedAt(desc ...bool) func(*gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if len(desc) > 0 && desc[0] {
			return db.Order("created_at desc")
		}
		return db.Order("created_at")
	}
}

func OrderByUpdatedAt(desc ...bool) func(*gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if len(desc) > 0 && desc[0] {
			return db.Order("updated_at desc")
		}
		return db.Order("updated_at")
	}
}
